package com.example.demo.typeHandler;

import com.example.demo.service.MqttService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.*;

import javax.annotation.Resource;

@Slf4j
public class MyWebSocketHandler implements WebSocketHandler {

    @Resource
    MqttService mqttService;

    @Override
    public void afterConnectionEstablished(WebSocketSession webSocketSession) throws Exception {

    }

    @Override
    public void handleMessage(WebSocketSession webSocketSession, WebSocketMessage<?> webSocketMessage) throws Exception {
        log.info("收到消息：" + webSocketMessage.getPayload());
        int getMessage = Integer.parseInt(webSocketMessage.getPayload().toString());
//        MqttService  mqttService = SpringContextHolder.getBean(MqttService.class);
        System.out.println("转为："+getMessage);
        String sendMessage = mqttService.publish(getMessage);
//        JSONObject js = JSONObject.parseObject(webSocketMessage.getPayload().toString());
//        System.out.println("消息体："+webSocketMessage);
        log.info("发送消息："+sendMessage);
        webSocketSession.sendMessage(new TextMessage(sendMessage));
    }

    @Override
    public void handleTransportError(WebSocketSession webSocketSession, Throwable throwable) throws Exception {

    }

    @Override
    public void afterConnectionClosed(WebSocketSession webSocketSession, CloseStatus closeStatus) throws Exception {

    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }
}
